package com.sfj.system.service.func;

import com.sfj.system.entity.FuncEntity;
import com.sfj.system.mapper.FuncMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kaka
 * @Date 2025/06/28
 */
@Service
public class FuncQueryService {

    @Resource
    private FuncMapper funcMapper;

    /**
     * 获取指定角色的菜单树
     */
    public List<FuncEntity> getMenuTreeByRole(Integer roleId) {
        List<FuncEntity> allMenus = funcMapper.selectFuncByRoleId(roleId);
        return buildTree(allMenus);
    }

    public List<FuncEntity> query(FuncEntity funcEntity) {
        List<FuncEntity> allMenus = funcMapper.query(funcEntity);
        return buildTree(allMenus);
    }
    /**
     * 构建菜单树结构
     */
    private List<FuncEntity> buildTree(List<FuncEntity> menuList) {
        Map<String, FuncEntity> idToNode = new HashMap<>();
        List<FuncEntity> rootList = new ArrayList<>();

        for (FuncEntity menu : menuList) {
            idToNode.put(menu.getFuncId(), menu);
        }

        for (FuncEntity menu : menuList) {
            if (menu.getUpFuncId() == null || !idToNode.containsKey(menu.getUpFuncId())) {
                rootList.add(menu); // 无上级，放到根节点
            } else {
                FuncEntity parent = idToNode.get(menu.getUpFuncId());
                parent.getChildren().add(menu);
            }
        }

        return rootList;
    }
}

